<template>
  <div class="score-detail-dialog">
    <div class="detail-header">
      <div class="header-info">
        <h3>📊 综合评分详情</h3>
        <p class="header-subtitle">业务日期: {{ bussDate }}</p>
      </div>
      <button 
        @click="exportToExcel" 
        class="btn-export"
      >
        📥 导出Excel
      </button>
    </div>

    <div class="detail-summary">
      <div class="summary-card">
        <div class="summary-label">支行总数</div>
        <div class="summary-value">{{ branchCount }}</div>
      </div>
      <div class="summary-card">
        <div class="summary-label">评分指标</div>
        <div class="summary-value">30 项</div>
      </div>
      <div class="summary-card success">
        <div class="summary-label">最高分</div>
        <div class="summary-value">{{ topScore.toFixed(2) }}</div>
      </div>
      <div class="summary-card">
        <div class="summary-label">平均分</div>
        <div class="summary-value">{{ avgScore.toFixed(2) }}</div>
      </div>
    </div>

    <div class="branches-list">
      <div 
        v-for="branch in sortedBranches" 
        :key="branch.orgNo"
        class="branch-card"
      >
        <div class="branch-header">
          <div class="branch-info">
            <h4>{{ branch.orgName }} ({{ branch.orgNo }})</h4>
            <div class="branch-tags">
              <span class="tag rank">排名 {{ branch.rank }}</span>
              <span class="tag score" :class="getScoreClass(branch.score)">
                {{ branch.score }}分
              </span>
            </div>
          </div>
          <div class="branch-stats">
            <div class="stat-item">
              <span class="stat-label">加权总分</span>
              <span class="stat-value">{{ branch.weightedScore.toFixed(2) }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">评级</span>
              <span class="stat-value">{{ getScoreLevel(branch.score) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, watch } from 'vue'

const props = defineProps({
  scoreData: {
    type: Object,
    required: true
  },
  bussDate: {
    type: String,
    default: '20250930'
  }
})

// 调试：监听数据变化
watch(() => props.scoreData, (newData) => {
  console.log('[ScoreDetailDialog] 接收到的数据:', newData)
  console.log('[ScoreDetailDialog] 数据条数:', Object.keys(newData).length)
}, { immediate: true })

// 排序后的支行列表
const sortedBranches = computed(() => {
  const branches = Object.values(props.scoreData).sort((a, b) => a.rank - b.rank)
  console.log('[ScoreDetailDialog] 排序后的支行列表:', branches.length, '个')
  return branches
})

// 统计数据
const branchCount = computed(() => Object.keys(props.scoreData).length)

const topScore = computed(() => {
  if (sortedBranches.value.length === 0) return 0
  return Math.round(sortedBranches.value[0].score)
})

const avgScore = computed(() => {
  if (sortedBranches.value.length === 0) return 0
  const sum = sortedBranches.value.reduce((acc, b) => acc + b.score, 0)
  return sum / sortedBranches.value.length
})

// 获取评分等级
const getScoreLevel = (score) => {
  if (score >= 90) return "优秀"
  if (score >= 85) return "良好"
  if (score >= 80) return "中等"
  if (score >= 75) return "预警"
  return "待改进"
}

// 获取评分样式类
const getScoreClass = (score) => {
  if (score >= 90) return 'excellent'
  if (score >= 85) return 'good'
  if (score >= 80) return 'fair'
  if (score >= 75) return 'warning'
  return 'poor'
}

// 导出Excel
const exportToExcel = () => {
  // 动态加载XLSX库（使用本地文件）
  if (window.XLSX) {
    performExport()
  } else {
    const script = document.createElement('script')
    // 根据环境选择路径
    if (import.meta.env.PROD) {
      script.src = '/coolv/vfs/root/products/ebi/sys/coolrpt/coolresource/libs/xlsx.full.min.js'
    } else {
      script.src = '/libs/xlsx.full.min.js'
    }
    script.onload = () => {
      performExport()
    }
    document.head.appendChild(script)
  }
}

const performExport = () => {
  try {
    const XLSX = window.XLSX
    
    // 准备导出数据
    const exportData = sortedBranches.value.map(branch => ({
      '排名': branch.rank,
      '支行名称': branch.orgName,
      '机构号': branch.orgNo,
      '综合得分': branch.score.toFixed(2),
      '加权总分': branch.weightedScore.toFixed(2),
      '总权重': branch.totalWeight,
      '评级': getScoreLevel(branch.score)
    }))
    
    const ws = XLSX.utils.json_to_sheet(exportData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '支行评分汇总')
    
    const fileName = `支行综合评分_${props.bussDate}_${new Date().toISOString().slice(0, 10)}.xlsx`
    XLSX.writeFile(wb, fileName)
    
    console.log('[导出Excel] 成功')
  } catch (err) {
    console.error('[导出Excel] 失败:', err)
    alert('导出Excel失败：' + err.message)
  }
}
</script>

<style scoped>
.score-detail-dialog {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100%;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-info h3 {
  margin: 0 0 5px 0;
  font-size: 20px;
  color: #1a1a1a;
}

.header-subtitle {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.btn-export {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-export:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.detail-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.summary-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.summary-card.success {
  background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
}

.summary-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 28px;
  font-weight: bold;
  color: #1a1a1a;
}

.branches-list {
  display: grid;
  gap: 15px;
}

.branch-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.branch-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.branch-header {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.branch-info h4 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #1a1a1a;
}

.branch-tags {
  display: flex;
  gap: 8px;
}

.tag {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.tag.rank {
  background: #e6f7ff;
  color: #1890ff;
}

.tag.score {
  font-weight: bold;
}

.tag.score.excellent {
  background: #f6ffed;
  color: #52c41a;
}

.tag.score.good {
  background: #e6f7ff;
  color: #1890ff;
}

.tag.score.fair {
  background: #fff7e6;
  color: #faad14;
}

.tag.score.warning {
  background: #fff2e8;
  color: #fa8c16;
}

.tag.score.poor {
  background: #fff2f0;
  color: #ff4d4f;
}

.branch-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.stat-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #1a1a1a;
}
</style>

